// 获取应用实例
const app = getApp();
let api = require('../../utils/api.js');
var QQMapWX = require('../../public/js/qqmap-wx-jssdk.min.js');
Page({
  data: {
    userLocationCity: '', // 用户当前所在城市
    background: [],
    vertical: false,
    interval: 2000,
    duration: 500,
    pageNum: 1,
    Height: "",
    orderAmount: Number,
    driverList: [], // 司机列表
    orderList: [], // 订单列表
    userTotal: Number,
    order_no: Number,
  },
  // 如果登陆了做这个动作
  getOnload() {
    var that = this;
    let token = wx.getStorageSync('TOKEN')
    let {
      userLocationCity,
      userLocationProvince
    } = app.globalData
    that.saveLocationCity(userLocationCity, userLocationProvince);
    app.getUserInfo().then((res) => {

      api._get('/omc/order/list/0', '', token).then(res3 => {
        if (res3.code == 200) {
          app.getRemind()

          that.setData({
            orderList: res3.result,
            orderAmount: res3.page.totalRow
          });
          if (res3.page.totalRow > 0) {
            that.getDriverList(token);
          }
        }
      })
    })
  },
  onLoad() {
    var that = this;
    // 实例化腾讯地图SDK
    var qqmapsdk = new QQMapWX({
      key: 'NT2BZ-Y5Q34-YYCUF-DLQNZ-KW3L5-TCFCC' // 必填
    });
    // var token = wx.getStorageSync('TOKEN');
    if (app.globalData.userLocationCity.length <= 1) {
      wx.getLocation({
        // type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude;
          var longitude = res.longitude;
          // 调用接口
          // 本接口提供由坐标到坐标所在位置的文字描述的转换，输入坐标返回地理位置信息和附近poi列表。
          qqmapsdk.reverseGeocoder({
            location: {
              latitude,
              longitude
            },
            success: function (res) {
              app.globalData.userLocationCity = res['result']['address_component']['city'];
              app.globalData.userLocation = {
                latitude,
                longitude
              }
              app.globalData.userLocationProvince = res['result']['address_component']['province']
              that.setData({
                userLocationCity: app.globalData.userLocationCity
              })
            }
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示 而得
   */
  onShow: function () {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    api._get('/banner/list/2', '', token).then(res1 => {
      if (res1.code == 200) {
        wx.getSystemInfo({
          success: function (res) {
            that.setData({
              pageNum: 1,
              background: res1.result,
              winWidth: res.windowWidth,
              winHeight: res.windowHeight - app.globalData.navHeight
            });
          }
        });
        api._get('/user/active/total', '', token).then(res2 => {
          if (res2.code == 200) {
            that.setData({
              userTotal: res2.result.total,
            })
          } else if (res2.code > 400) {}
        });
        that.setData({
          userLocationCity: app.globalData.userLocationCity
        })
      }
    })
    if (wx.getStorageSync('TOKEN')) {
      that.getOnload()
    }
  },

  changeIndicatorDots() {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },

  changeAutoplay() {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },

  intervalChange(e) {
    this.setData({
      interval: e.detail.value
    })
  },

  durationChange(e) {
    this.setData({
      duration: e.detail.value
    })
  },
  // 轮播图宽高自适应
  imgHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    //等比设置swiper的高度。即 图片宽度 / 图片高度 = 屏幕宽度 / swiper高度 ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度。此处单位为 px，不能是 rpx。
    var swiperH = winWid * imgh / imgw + "px";
    this.setData({
      Height: swiperH //设置高度，此处不能加;
    })
  },
  // 上传用户当前定位
  saveLocation: function (latitude, longitude) {
    var param = {
      "lat": latitude,
      "lng": longitude
    }
    var token = wx.getStorageSync('TOKEN');
    api._put('/location/push', param, token).then(res => {})
  },
  //加载更多
  onLoadMore: function (e) {
    var callback = e.detail;
    var that = this;
    var param = {
      pageNum: that.data.pageNum + 1,
      pageSize: 5
    };
    that.setData({
      pageNum: that.data.pageNum + 1
    })
    setTimeout(function () {
      var token = wx.getStorageSync('TOKEN');
      that.getDriverList(token, param, true);
      callback.success();
    }, 3000)
  },
  // 获取司机列表
  getDriverList: function (token, param, loadMore) {
    var that = this;
    let params = {}
    if (params) {
      params = params
    } else {
      params = {
        pageNum: 1,
        pageSize: 5
      }
    }
    api._get('/user/chauffeur/list', param, token).then(res => {
      if (res.code == 200) {
        res.result.forEach(function (value, index) {
          var activeState = '';
          console.log(value);
          if (value.activeState == 1) {
            activeState = '空闲';
          } else if (value.activeState == 0) {
            activeState = "忙碌";
          }
          res.result[index]['showActiveState'] = activeState;
          if (value.nickname == null) {
            res.result[index]['nickname'] = '司机';
          }
        });
        if (loadMore) {
          if (param.pageNum <= res.page.totalPage) {
            var showData = [...that.data.driverList, ...res.result];
            that.setData({
              driverList: showData
            })
          } else {
            wx.showToast({
              title: '没有更多订单',
              icon: 'none',
            })
            return false
          }
        } else {
          that.setData({
            driverList: res.result
          })
        }
      } else {
        wx.showToast({
          title: '网络忙请重试',
          icon: 'none',
        })
      }

    });
  },
  // 页面上滑 滚动触底事件
  // onReachBottom() {
  //   console.log('1');
  //   // 1. 判断还有没有下一页数据
  //   if (this.params.pageSize >= this.totalPages) {
  //     wx.showToast({
  //       title: '没有下一页数据'
  //     });
  //   } else {
  //     this.params.pageSize++;
  //     this.getDriverList();
  //   }
  // },
  onRefresh: function (e) {
    var callback = e.detail;
    var that = this;
    setTimeout(function () {

      that.onShow();
      callback.success();
    }, 3000)
  },
  /*
   * 弹出邀请接单
   */
  invite: function (e) {
    var that = this;
    var state = wx.getStorageSync('STATE');
    if (state == -2) {
      wx.showToast({
        title: '您的账户已被停用,需要跟工作人员联系恢复功能',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    var userId = e.currentTarget.dataset.driverid;
    var driver = e.currentTarget.dataset.drivername;
    var item = e.currentTarget.dataset.index;
    var driverstate = e.currentTarget.dataset.driverstate;

    if (driverstate == 0) {
      wx.showToast({
        title: '该司机忙碌状态，暂不接单，请邀请另一位司机吧',
        icon: 'none'
      })
      return;
    }

    var inviteData = {
      userId: userId,
      driver: driver,
      item: item
    }

    that.setData({
      inviteData: inviteData
    })
    // 显示遮罩层
    if (that.data.orderList.length == 1) {
      that.confirmSendOrder(inviteData, that.data.orderList[0].orderNo, that.data.orderList[0].id);
    } else {

      var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "linear",
        delay: 0
      })
      that.animation = animation
      animation.translateY(300).step()
      that.setData({
        animationData: animation.export(),
        showModelStatus: true
      })
      setTimeout(function () {
        animation.translateY(0).step()
        that.setData({
          animationData: animation.export()
        });
      }.bind(that), 200)
    }


  },
  laternext: function (e) {
    var that = this
    that.setData({
      score: e.detail.value,
    })
  },
  confirmFreight: function (e) {
    var that = this;
    var inviteData = that.data.inviteData;
    var value = that.data.score;

    var orderNo = that.data.orderList[value].orderNo;
    var score = that.data.orderList[value].id;
    that.confirmSendOrder(inviteData, orderNo, score);
  },
  confirmSendOrder: function (data, orderNo, orderId) {
    var that = this;
    var userId = data.userId;
    var driver = data.driver;
    var item = data.item;
    var driverList = that.data.driverList;

    wx.showModal({
      title: '提示',
      content: '确定邀请"' + driver + '"接订单编号为：' + orderNo + '的订单吗',
      cancelText: '取消',
      confirmText: '确定',
      success(res) {
        if (res.cancel) {
          // 用户点击了取消属性的按钮
        } else if (res.confirm) {
          // 用户点击了确定属性的按钮
          var token = wx.getStorageSync('TOKEN');
          var param = {
            "userId": userId,
            "id": orderId
          }
          api._post('/omc/order/invite', param, token).then(res => {
            driverList[item]['state'] = 0;
            // console.log(res);
            if (res.code == 200) {
              that.hideModal();
              that.setData({
                driverList: driverList
              })

            } else if (res.code > 400) {
              if (res.code == 30000008) {
                wx.showToast({
                  title: res.message,
                  icon: 'none'
                })
              } else {

                wx.navigateTo({
                  url: '../login/authUser/index',
                })
              }
            } else {
              wx.showToast({
                title: '网络忙请重试',
                icon: 'none',
              })
            }
          }).catch(e => {})
        }
      }
    })

  },
  createOrder: function () {
    var state = wx.getStorageSync('STATE');

    if (!wx.getStorageSync('TOKEN')) {
      app.goAuthpPages()
    } else {
      if (state == 1) {
        wx.navigateTo({
          url: '../order/createOrder/createOrder',
        })
      } else if (state == -2) {
        wx.showToast({
          title: '您的账户已被停用,需要跟工作人员联系恢复功能',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '您还没有通过认证，为了不影响您的使用，请及时认证',
          cancelText: '取消',
          confirmText: '确定',
          success(res) {
            if (res.cancel) {
              // 用户点击了取消属性的按钮
            } else if (res.confirm) {
              // 用户点击了确定属性的按钮
              wx.navigateTo({
                url: '../user/authentication/authentication',
              })
            }
          }
        })
      }

    }

  },
  /**
   * 上传城市名称
   */
  saveLocationCity(city, province) {

    var param = {
      "city": city,
      "province": province
    }
    var token = wx.getStorageSync('TOKEN');
    api._put('/location/city', param, token).then(res => {
      if (res.code == 200) {
        wx.switchTab({
          url: '../../index/index',
          success: function (e) {}
        })
      }
    })
  },

  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      keyboardHeight: 0
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModelStatus: false,
        keyboardHeight: 0
      })
    }.bind(this), 200)
  },

  goto: function (e) {
    var url = e.currentTarget.dataset.url;
    if (url != '') {
      wx.navigateTo({
        url: '/pages/gotoUrl/index?url=' + url,
      })
    }

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    if (res.from === 'button') {
      console.log('来自页面内转发按钮');
      wx.switchTab({
        url: '/pages/index/index'
      })
      this.setData({
        showShareModelStatus: false
      })
    } else if (res.from === 'menu') {
      console.log(res.from);
      console.log('右上角菜单转发按钮');
    }
  },
})